<template>
	<view class="pad_def pad_top" style="background-color: #fff;">
		<view><u-toast ref="uToast" /></view>
		<u-form :model="form" ref="uForm" style="padding: 50rpx;">
			<u-form-item label="应用上传:" label-width="200rpx" label-position="left">
				<u-button type="primary" size="mini" @click="selectApk">选择应用</u-button>
				<u-line-progress v-if="showProgress" active-color="#2979ff" :percent="progress" height="25"></u-line-progress>
			</u-form-item>
			<u-form-item label="应用名称" label-width="200rpx" label-position="left" prop="app_name">
				<!-- <view>{{form.app_name}}</view> -->
				<u-input v-model="form.app_name"></u-input>
			</u-form-item>
			<u-form-item label="应用包名:" label-width="200rpx" label-position="left" prop="app_package">
				<view>{{form.app_package}}</view>
			</u-form-item>
			<u-form-item label="版本号:" label-width="200rpx" label-position="left" prop="app_version_name">
				<view>{{form.app_version_name}}</view>
			</u-form-item>
			<u-form-item label="内部版本号:" label-width="200rpx" label-position="left" prop="app_version_code">
				<view>{{form.app_version_code}}</view>
			</u-form-item>

			<u-form-item label="应用大小:" label-width="200rpx" label-position="left">
				<view>{{form.showSize}}</view>
			</u-form-item>
			<u-form-item label="应用图标:" label-width="200rpx" label-position="left" prop="app_img">
				<view style="display: flex; justify-content: flex-end; align-items: center; width: 80%;">
					<u-image width="100rpx" mode="widthFix" shape="circle" :src="form.app_img" border-radius="50rpx" @click="selectFile"></u-image>
				</view>
			</u-form-item>
			<u-form-item label="应用类型:" label-width="200rpx" label-position="left">
				<u-radio-group v-model="form.app_attribution" @change="radioGroupChange">
					<u-radio v-for="(item, index) in typeList" :key="index" :name="item.value">
						{{item.name}}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<!-- <u-form-item label="强制安装:" label-width="200rpx" label-position="left" prop="app_forceinstall" v-if="form.app_attribution==1">
				<u-switch v-model="form.app_forceinstall"></u-switch>
			</u-form-item> -->
			<u-form-item label="应用分类:" label-width="200rpx" label-position="left" prop="category">
				<u-input v-model="form.category" type="select" @click="showCategory = true" />
			</u-form-item>
		</u-form>
		<u-select v-model="showCategory" :list="categoryList" value-name="id" label-name="name" @confirm="setCategory"></u-select>
		<view style="padding-bottom: 20rpx; display: flex; justify-content: center;">
			<u-button class="enter" :custom-style="enter" shape="square" @click="addApk">提交</u-button>
		</view>
	</view>
</template>

<script>
	import {
		addSelfApp,
		getCateGory,
		getOssApkDetail,
		getAllAppMd5,
		isUploadApkDetail
	} from '../../../api/application';
	import {
		ossImage,
		ossUploadApk
	} from '../../../utils/ossUpload';
	import {
		getBaseUrl
	} from '../../../utils/http.js';
	export default {
		data() {
			return {
				form: {
					'app_name': '',
					'app_package': '',
					'app_version_name': '',
					'app_version_code': 0,
					'app_size': '',
					'app_url': '',
					'app_img': '',
					'app_md5': '',
					'bg': '',
					'app_attribution': 0,
					'app_forceinstall': false,
					'showSize': '',
					'app_category_id': '0',
					'category': ''
				},
				baseUrl: '',
				typeList: [{
						name: '公用应用',
						value: 0,
					},
					{
						name: '专属应用',
						value: 1,
					}
				],
				rules: {
					app_name: [{
						required: true,
						message: '未获取到应用名称',
						trigger: 'blur'
					}],
					app_package: [{
						required: true,
						message: '未获取到包名',
						trigger: 'blur'
					}],
					app_version_name: [{
						required: true,
						message: '未获取到应用版本号',
						trigger: 'blur'
					}],
					// app_version_code: [{
					// 	required: true,
					// 	message: '未获取到应用内部版本号',
					// 	trigger: ['change','blur']
					// }],
					app_size: [{
						required: true,
						message: '未获取到应用大小',
						trigger: 'blur'
					}],
					app_url: [{
						required: true,
						message: '未获取到应用下载地址',
						trigger: 'blur'
					}],
					app_img: [{
						required: true,
						message: '请选择应用图标',
						trigger: 'blur'
					}],
					app_md5: [{
						required: true,
						message: '未获取到app_md5',
						trigger: 'blur'
					}],
					bg: [{
						required: true,
						message: '未获取到包名',
						trigger: 'blur'
					}],
					category: [{
						required: true,
						message: '请选择应用分类',
						trigger: 'blur'
					}],
				},
				enter: {
					'color': '#FFFFFF',
					'background-color': '#4880ff',
					'letter-spacing': '8rpx',
					'border-radius': '20rpx',
					'line-height': '80rpx',
					'overflow': 'hidden',
					'font-weight': '600',
					'margin-top': '30rpx',
					'width': '400rpx',
					'borderRadius': '50rpx'
				},
				showCategory: false,
				categoryList: [],
				progress: 0,
				showProgress: false,
				allAppMd5: [],
			}
		},
		onLoad() {
			this.baseUrl = getBaseUrl()
			this.getMiniCategory()
			this.getAllAppMd5Method()
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			selectApk() {
				wx.showLoading({
					title: '正在努力解析中...',
					mask: true,
				});
				let that = this
				uni.chooseMessageFile({
					count: 1, //默认100
					type: 'all',
					extension: ['.apk'],
					success: function(res) {
						let tempFile = res.tempFiles[0];
						let tempFilePaths = tempFile.path; //本地临时路径
						let name = tempFile.name;
						let size = tempFile.size;
						let api = 'api/getOssApkDetail'
						let host = that.baseUrl + api
						let app_md5 = ''
						that.showProgress = true
						uni.getFileInfo({
							filePath: tempFilePaths,
							success: function(res) {
								app_md5 = res.digest
								let isUpload = false;
								if (app_md5 != '' && that.allAppMd5.length > 0) {
									that.allAppMd5.forEach((value, index, arr) => {

										if (value == app_md5) {
											isUpload = true
										}
									})
								}
								if (isUpload) {
									that.progress = 100
									that.isUploadApkDetail(app_md5)
									wx.hideLoading();
								} else {
									ossUploadApk(name, tempFilePaths).then(res => {
										that.form.app_url = res
									}).catch(err => {
										console.log("上传失败", err)
									})
									const uploadTask = uni.uploadFile({
										url: host,
										filePath: tempFilePaths,
										name: 'file',
										formData: {
											userId: 2,
											file_name: name,
											size: size,
											app_md5: app_md5
										},
										success: (res) => {
											let result = JSON.parse(res.data)
											let data = result.data
											that.form.app_name = data.app_name
											that.form.app_package = data.app_package
											that.form.app_version_name = data.app_version_name
											that.form.app_version_code = data.app_version_code
											that.form.app_size = size
											that.form.showSize = data.showSize
											that.form.bg = data.bg
											that.form.app_img = data.app_img
											that.form.app_md5 = data.app_md5
											wx.hideLoading();
										},
										fail: (err) => {
											that.$refs.uToast.show({
												title: '上传失败',
												icon: false,
												type: 'error'
											})
											wx.hideLoading();
										}
									})
									uploadTask.onProgressUpdate((res) => {
										that.progress = res.progress
									})
								}
							},
							fail: function(err) {
								console.log("失败", err)
							}
						})

					}
				});
			},
			selectFile() {
				let that = this
				uni.chooseImage({
					count: 1, // 默认最多一次选择9张图
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: function(res) {
						let tempFilePaths = res.tempFilePaths; //本地临时路径
						ossImage(tempFilePaths[0]).then(res => {
							that.form.app_img = res
						}).catch(err => {
							that.$refs.uToast.show({
								title: '上传失败',
								icon: false,
								type: 'error'
							})
						})
					}
				})
			},
			radioGroupChange(e) {
				this.form.app_attribution = e
			},
			addApk() {
				console.log(this.form)
				this.$refs.uForm.validate(valid => {
					let addForm = JSON.parse(JSON.stringify(this.form))
					addForm.id = uni.getStorageSync('snId'),
						addForm.userId = uni.getStorageSync('userId'),
						addForm.last_ip = uni.getStorageSync('Ip')
					if (valid) {
						addSelfApp(addForm).then(res => {
							this.$refs.uToast.show({
								title: res.msg,
								type: 'success',
								icon: false
							})
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								});
							}, 500)
						}).catch(err => {
							this.$refs.uToast.show({
								title: err.msg,
								icon: false,
								type: 'error'
							})
						})
					} else {}
				});
			},
			getMiniCategory() {
				getCateGory().then(res => {
					this.categoryList = res.data
				}).catch(err => {})
			},
			setCategory(e) {
				this.form.app_category_id = e[0].value
				this.form.category = e[0].label
			},
			getAllAppMd5Method() {
				getAllAppMd5().then(res => {
					this.allAppMd5 = res.data.appMd5
				}).catch(err => {})
			},
			isUploadApkDetail(app_md5) {
				isUploadApkDetail({
					app_md5: app_md5
				}).then(res => {
					let data = res.data
					this.form.app_name = data.app_name
					this.form.app_package = data.app_package
					this.form.app_version_name = data.app_version_name
					this.form.app_version_code = data.app_version_code
					this.form.app_size = data.app_size
					this.form.showSize = data.showSize
					this.form.bg = data.bg
					this.form.app_url = data.app_url
					this.form.app_md5 = data.app_md5
					this.form.app_img = data.app_img
				}).catch(err => {

				})
			}
		}
	}
</script>